package e2q.security.web.manage;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import e2q.di.web.util.PmUserSession;
import e2q.security.domain.E2qSmSystemMenu;
import e2q.web.mvc.UrlAuthenticate;
import e2q.web.session.UserSession;

public class UrlAuthenticateImpl implements UrlAuthenticate {
	private List<String> excludedUrlList = new ArrayList<String>();
	private List<String> excludedUrlLists = new ArrayList<String>();
	public UrlAuthenticateImpl(){
		Properties p = new Properties();
		try {
			InputStream is = getClass().getResourceAsStream(
					"/edu/yale/its/tp/cas/client/filter/impl/excludedUrl.properties");
			p.load(is);
			is.close(); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		String[] urlList = p.getProperty("passSecurityUrl").split(",");
		String[] urlLists = p.getProperty("passSecurityUrls").split(",");
		for(String s : urlList){
			excludedUrlList.add(s);
		}
		for(String s : urlLists){
			excludedUrlLists.add(s);
		}
	}
	public boolean checkUrl(String url, UserSession userSession) {
		if (userSession != null && userSession.isEnabled()) {
			if (url.startsWith("/common/main") || url.startsWith("/exception") || url.endsWith(".do")) {
				return true;
			}
			PmUserSession pUserSession = (PmUserSession) userSession;
			List<String> resUrlList = (List<String>) pUserSession.getFunctions();
			for(String uri : resUrlList){
				if (uri != null && !uri.trim().equals("")) {
					String u = uri.split("[?]")[0];
					if (url.equals(u)) {
						return true;
					}
				}
			}
			return false;
			
		}else {
			return false;
		}
	}

	public boolean passUrl(String url) {
		int s=url.indexOf("/",1)>1?url.indexOf("/",1):1;
		String urlString=url.substring(1,s).trim().toLowerCase();
		if (excludedUrlList.contains(url)||excludedUrlLists.contains(urlString)) {
			return true;
		}else {
			return false;
		}
	}
	public boolean isLogin(HttpServletRequest arg0) {
		String session=(String) arg0.getSession().getAttribute("edu.yale.its.tp.cas.client.filter.user");
		  if(session!=null&&!session.equals(""))
		  {
			  return true;
		  }else {
			return false;
		}
	}
}
